﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using aspZone.Commerce.DataAccess;
using aspZone.Commerce.Model;

namespace aspZone.Commerce.Web.App.Controllers
{
    [HandleError]
    public class CartController : Controller
    {
        private IOrderRepository orderRepository;
        private IProductRepository productRepository;
        private ICategoryRepository categoryRepository;

        public CartController(IOrderRepository orderRepository, IProductRepository productRepository, ICategoryRepository categoryRepository)
        {
            this.orderRepository = orderRepository;
            this.productRepository = productRepository;
            this.categoryRepository = categoryRepository;
        }

        public ActionResult Index()
        {
            ViewData.Model = this.GetOrder();
            return View();
        }

        public ActionResult Add(int id)
        {
            Product product = this.productRepository.Get(id);
            Order order = this.GetOrder();
            order.AddItem(product);
            this.SaveOrder(order);
            return RedirectToAction("Index");
        }

        public ActionResult Remove(int id)
        {
            Product product = this.productRepository.Get(id);
            Order order = this.GetOrder();
            order.RemoveItem(product);
            this.SaveOrder(order);
            return RedirectToAction("Index");
        }

        public ActionResult Update()
        {
            Order order = this.GetOrder();

            foreach (var item in order.Items)
            {
                string key = "ProductId" + item.Product.Id;
                if (Request.Form.AllKeys.Contains(key))
                {
                    int quantity = int.Parse(Request.Form[key]);
                    order.AdjustQuantity(item.Product, quantity);
                }
            }

            this.SaveOrder(order);
            return RedirectToAction("Index");
        }

        private Order GetOrder()
        {
            Order order = null;

            // Try to read the CartId cookie
            var cookie = Request.Cookies["CartId"];
            if (cookie != null)
            {
                int cartId = 0;
                if (int.TryParse(cookie.Value, out cartId))
                {
                    // Try to get the order from the repository
                    order = this.orderRepository.Get(cartId);
                }
            }

            // If no order found, create a new one
            if (order == null)
            {
                order = new Order();
            }

            return order;
        }

        private void SaveOrder(Order order)
        {
            // Save the order to the repository
            this.orderRepository.SaveOrUpdate(order);
            this.orderRepository.CommitChanges();

            // Write the CartId cookie
            var cookie = new HttpCookie("CartId");
            cookie.Value = order.Id.ToString();
            cookie.Expires = DateTime.Now.AddDays(1);
            Response.Cookies.Add(cookie);
        }

        protected override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            if (filterContext.Result is ViewResult)
            {
                MasterPageViewDataHelper.AddViewDataRequiredByMasterPage(this.HttpContext.Cache, this.ViewData, this.categoryRepository); ;
            }
        }
    }
}
